package cn.bdqn.service.impl;


import cn.bdqn.dao.UserDao;
import cn.bdqn.entity.Role;
import cn.bdqn.entity.User;
import cn.bdqn.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    UserDao userDao;

    @Override
    public User login(String usrName, String usrPassword) {
        //执行查询
        User user = userDao.findByUsrNameAndUsrPassword(usrName,usrPassword);
        return user;
    }

    @Override
    public void addUser(User user) {
        userDao.save(user);
    }

    @Override
    public void updateUser(User user) {
        userDao.save(user);
    }

    @Override
    public void deleteUser(Long id) {
        userDao.deleteById(id);
    }

    @Override
    public User getUser(Long id) {
        return userDao.findById(id).get();
    }

    @Override
    public Page<User> getUsersByPage(String usrName, Long roleId,
                                     Integer pageNo, Integer pageSize) {
        //组装排序条件
        Sort sort=new Sort(Sort.Direction.DESC,"usrId");

        //组装分页条件
        Pageable pageable= PageRequest.of(pageNo,pageSize,sort);

        //组装过滤条件
        Specification<User> sf=new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root,
                                         CriteriaQuery<?> criteriaQuery,
                                         CriteriaBuilder cb) {
                //1.构造条件 动态判断
                List<Predicate> list=new ArrayList<>();
                if(usrName!=null&&!usrName.equals("")){
                    list.add(cb.like(root.get("usrName"), "%"+usrName+"%"));
                }
                if(roleId!=null){
                    Role role=new Role();
                    role.setRoleId(roleId);
                    list.add(cb.equal(root.get("role"), role));
                }
                //2.多个条件用and连接起来成一个条件
                Predicate and = cb.and(list.toArray(new Predicate[list.size()]));
                return and;
            }
        };
        //调用分页方法
        Page<User> page = userDao.findAll(sf, pageable);
        //返回分页对象
        return page;
    }

}
